<?php

class Upload {
	
	private $allowedExt = '*.*';

	public function __construct($fileInfo, $uploadPath = './uploads/') {
		
	    $this->uploadPath = $uploadPath;
		$this->fileInfo = $fileInfo;

		if(!file_exists($this->uploadPath)) {
			die("Upload directory doesn't exist!");
		}

		if(!is_writeable($this->uploadPath)) {
			die("Upload directory is not writeable.");
		}
		
		if(empty($fileInfo)) {
			die('Incorrect file array sent');
		}
		
	}

	public function setExtensions($ext) {
		
	    if(!is_array($ext)) {
			die('Valid extensions must be passed as an array.');
		}
		
		$this->allowedExt = $ext;
	}

	public function upload() {
		
	    $results = array();
	    $uploadFile = uniqid(rand(), true).'_'.substr(sha1($this->fileInfo['name']), 0, 8);
	    			
		# Mimes match, so ensure that it's only 
		$ext = end(explode(".", $this->fileInfo['name']));
            
		# Valid file extension
		if(in_array(".$ext", $this->allowedExt)) {
			
			# Move uploaded file
			if(@move_uploaded_file($this->fileInfo['tmp_name'], $this->uploadPath.$uploadFile.".$ext")) {
					
				$results['error'] = false;
				$results['filename'] = $uploadFile.".$ext";
				$results['reason'] = '';

				return $results;
					
			} else {
					
				$results['error'] = true;
				$results['filename'] = '';
				$results['reason'] = 'File upload failed.';
					
			}
				
		} else {
				
			$results['error'] = true;
			$results['filename'] = $uploadFile.".$ext";
			$results['reason'] = 'Invalid file extension';
				
		}
	    
	    return $results;
		
	}
	
}
?>